package com.zzyl.framework.interceptor;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    // 判断是否为会员相关请求
    public boolean ifUseUserId() {
        try {
            String uri = request.getRequestURI();
            return !uri.contains("/member");
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 使用LocalDateTime类型填充
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());

        if (ifUseUserId()) {
            this.strictInsertFill(metaObject, "createBy", String.class, loadUserId() + "");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 使用LocalDateTime类型填充
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        if (ifUseUserId()) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, loadUserId() + "");
        }
    }

    /**
     * 获取当前登录用户ID
     */
    public static Long loadUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return ObjectUtils.isNotEmpty(loginUser) ? loginUser.getUserId() : 1L;
    }
}
